﻿using System;
using System.Net.Mail;
using System.Text;
using System.Web.Mvc;
using System.Web.Security;
using HiLand.Framework.BusinessCore;
using HiLand.Framework.BusinessCore.BLL;
using HiLand.Utility.Entity;
using HiLand.Utility.Enums;

namespace GBFinance.Web.Areas.UserCenter.Controllers
{
    public class MainController : Controller
    {
        /// <summary>
        /// 登录页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 登录页面
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Index(string userName, string password)
        {
            LogicStatusInfo logicStatusInfo = new LogicStatusInfo();
            LoginStatuses loginStatus = LoginStatuses.Successful;
            BusinessUser businessUser = null;

            if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password))
            {
                logicStatusInfo.IsSuccessful = false;
                logicStatusInfo.Message = "Please must enter your account and password first!";
            }
            else
            {
                businessUser = BusinessUserBLL.Login(userName, password, out loginStatus);

                if (loginStatus == LoginStatuses.Successful)
                {
                    logicStatusInfo.IsSuccessful = true;
                }
                else
                {
                    logicStatusInfo.IsSuccessful = false;
                    logicStatusInfo.Message = loginStatus.ToString();
                }
            }

            if (logicStatusInfo.IsSuccessful == true)
            {
                if (FormsAuthentication.GetRedirectUrl(userName, false) == FormsAuthentication.DefaultUrl)
                {
                    switch (businessUser.UserType)
                    {
                        case UserTypes.Broker:
                            return RedirectToAction("Index", "Main", new { area = "Broker" });
                        case UserTypes.Manager:
                        case UserTypes.SuperAdmin:
                            return RedirectToAction("Index", "Main", new { area = "Manage" });
                        default:
                            break;
                    }
                }
                
                FormsAuthentication.RedirectFromLoginPage(userName, false);
            }

            return View(logicStatusInfo);
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <returns></returns>
        public ActionResult Logout()
        {
            BusinessUserBLL.Logout();
            return RedirectToAction("Index", "Main");
        }

        /// <summary>
        /// 忘记口令
        /// </summary>
        /// <returns></returns>
        public ActionResult ForgottenPassword()
        {
            return View();
        }
        
        [HttpPost]
        public ActionResult ForgottenPassword(string userName)
        {
            LogicStatusInfo logicStatusInfo = new LogicStatusInfo();

            BusinessUser businessUser = null;

            if (string.IsNullOrWhiteSpace(userName))
            {
                logicStatusInfo.IsSuccessful = false;
                logicStatusInfo.Message = "Please must enter your account first!";
            }
            else
            {
                businessUser = BusinessUserBLL.Get(userName);

                if (businessUser != null && businessUser.IsEmpty== false)
                {
                    try
                    {
                        using (SmtpClient smtpClient = new SmtpClient())
                        {
                            MailMessage mailMessage = GetMail(businessUser);
                            smtpClient.Send(mailMessage);
                        }

                        logicStatusInfo.IsSuccessful = true;
                        logicStatusInfo.Message = "the password you request has been sent to your email.";
                    }
                    catch 
                    {
                        logicStatusInfo.IsSuccessful = false;
                        logicStatusInfo.Message = "The user you requst does not exist,or the user has no email.";
                    }
                }
                else
                {
                    logicStatusInfo.IsSuccessful = false;
                    logicStatusInfo.Message = "The user you requst does not exist.";
                }
            }

            return View(logicStatusInfo);
        }

        /// <summary>
        /// 修改口令
        /// </summary>
        /// <returns></returns>
        public ActionResult _ChangePassword()
        {
            PassCurrentUser();
            return View();
        }

        /// <summary>
        /// 修改口令
        /// </summary>
        /// <param name="userGuid"></param>
        /// <param name="passwordOld"></param>
        /// <param name="passwordNew"></param>
        /// <param name="passwordNewConfirm"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult _ChangePassword(Guid userGuid, string passwordOld, string passwordNew, string passwordNewConfirm)
        {
            LogicStatusInfo logicStatusInfo = new LogicStatusInfo();
            logicStatusInfo.IsSuccessful = BusinessUserBLL.ChangePassword(userGuid, passwordNew, passwordOld);

            PassCurrentUser();
            return View(logicStatusInfo);
        }

        #region 辅助方法
        private void PassCurrentUser()
        {
            BusinessUser currentUser = BusinessUserBLL.CurrentUser;
            this.ViewBag.CurrentUser = currentUser;
        }
        #endregion

        #region 辅助方法
        /// <summary>
        /// 构建发送的邮件信息
        /// </summary>
        /// <param name="brokerEntity"></param>
        /// <returns></returns>
        [NonAction]
        private MailMessage GetMail(BusinessUser brokerEntity)
        {
            MailMessage mailMessage = new MailMessage();
            mailMessage.IsBodyHtml = true;
            MailAddress fromAddress = new MailAddress("cashsolution.com.au@gmail.com", "Golden Bridge Finance");
            MailAddress toAddress = new MailAddress(brokerEntity.UserEmail, brokerEntity.UserNameJointing);

            mailMessage.From = fromAddress;
            mailMessage.To.Add(toAddress);
            mailMessage.Subject = "You have successfully retrieve password from Golden Bridge Finance";

            StringBuilder messageBody = new StringBuilder();
            messageBody.AppendLine("Dear Sir/Madam,<br/>");
            messageBody.Append("You have successfully retrieve  password from Golden Bridge Finance.<br/>");
            messageBody.AppendFormat("Your password is : {0}<br/>", brokerEntity.Password);
            messageBody.Append("<br/><br/>");
            messageBody.Append("Kind Regards,");
            messageBody.Append("<br/>");
            messageBody.Append("The team of Golden Bridge Finance");

            mailMessage.Body = messageBody.ToString();

            return mailMessage;
        }
        #endregion
    }
}
